/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-12-7 上午11:57 Created by dwzhang
 */
package com.jade.modules.message.service.impl;

import java.util.Date;
import java.util.List;

import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.base.log.Log;
import com.jade.framework.base.log.LogUtils;
import com.jade.framework.mom.MessageListener;
import com.jade.framework.mom.MomMessage;
import com.jade.modules.message.service.Message;
import com.jade.modules.message.service.MessageService;

/**
 * 队列消息处理侦听器。.
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-12-7 上午11:57
 */
public class MessageQueueListener
        implements MessageListener
{
    protected Log log = LogUtils.getLog(this.getClass());
    private MessageService messageService;

    public MessageService getMessageService()
    {
        if (messageService == null) {
            messageService = ApplicationContextUtils.getBean("module_messageService");
        }
        return messageService;
    }

    public boolean consumeMessage(List<MomMessage> messages)
    {
        //考虑到每个消息的处理方式，消息将采用单个出队的方式来进行
        MomMessage momMessage = messages.get(0);
        Message message = (Message) momMessage.getMsg();
        log.info("Pop message ", message);
        Date current = new Date();
        if (message.getScheduleTime() != null && message.getScheduleTime().getTime() - current.getTime() > 1000) {
            try {
                ((MessageServiceImpl) getMessageService()).enqueueMessage(message);
                return true;
            }
            catch (Exception e) {
                log.warnThrowable("Can't put scheduled message to queue " + message.getId(), e);
                return false;
            }
        }

        try {
            ((MessageServiceImpl) getMessageService()).process(message, false);
            return true;
        }
        catch (Throwable t) {
            log.warnThrowable("Can't process message " + message.getId(), t);
            return false;
        }
    }
}